package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private QiniuUtils qiniuUtils;
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        log.info("[套餐新增]setmeal:{},checkgroupIds:{}",setmeal,checkgroupIds);
        setMealService.add(setmeal,checkgroupIds);
        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
    }
    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean){
        PageResult pageResult = setMealService.findPage(queryPageBean);
        return  new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,pageResult);
    }
    @PostMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile multipartFile) {
        log.info("文件上传，name:{},size:{}", multipartFile.getOriginalFilename(), multipartFile.getSize());
        //原始文件名
        String originalFileName = multipartFile.getOriginalFilename();
        //使用UUID构造不重复的文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + "_" + originalFileName;

        //获取输入流并上传
        try (InputStream is = multipartFile.getInputStream()) {
            qiniuUtils.upload2Qiniu(is, fileName);
        } catch (IOException e) {
            log.error("", e);
            return new Result(false, MessageConst.PIC_UPLOAD_FAIL);
        }

        //构造返回值
        String pic = qiniuUtils.getUrlPrefix() + fileName;
        return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS, pic);
    }
}
